package com.hxrk.cecardvr;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.hxrk.easyface.EasyFace;
import com.hxrk.jni.Mp4v2Native;

import java.io.File;

/**
 * 人脸识别服务
 * Created by Administrator on 2018/6/13.
 */
public class FaceService extends Service {
    private Context mContext;


    public static String ACTION_FACERECEIVER = "com.hxrk.cecardvr.faceservice";

    //人脸识别标识 0：不开启  1：开启
    public static int FaceStatus = 0;

    private boolean isShowTips = false;

    private OnFaceListener onFaceListener;

    private static EasyFace.OnSubFaceListener listener;
    private String files[] = {"seeta_fa_v1.1.bin", "seeta_fd_frontal_v1.0.bin"};
    private static String facesPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DidiMain/faces/";
    private String faceServerIP = "39.108.224.241";
    private int faceServerPort = 65400;
    private String faceDriverID = "144312";

    // 人脸数
    public static int FaceNumber = 0;


    /**
     * 显示提示信息
     *
     * @param text
     */
    private void showToast(String text) {

    }

    public interface OnFaceListener {
        void onMessage(String faceID);

        void onFaceNumber(int faceNumber);

        void onStopFace();
    }

    public void setOnFaceListener(OnFaceListener listener) {
        onFaceListener = listener;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
//        return null;
        return new FaceServiceBinder();
    }

    public class FaceServiceBinder extends Binder {
        public FaceService getService() {
            return FaceService.this;
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d("onCreate: ");
        mContext = getApplicationContext();

        //注册广播
        registerReceiver();

        for (int i = 0; i < files.length; i++) {
            File file = new File(facesPath + files[i]);
            if (!file.exists()) {

                FileUtils.getInstance(mContext).copyAssetsToSD("faces", "DidiMain/faces").setFileOperateCallback(new FileUtils.FileOperateCallback() {
                    @Override
                    public void onSuccess() {
                        LogUtils.i("onSuccess");
                        // TODO: 文件复制成功时，主线程回调
                    }

                    @Override
                    public void onFailed(String error) {
                        LogUtils.i("onFailed");
                        // TODO: 文件复制失败时，主线程回调
                    }
                });
            }
        }
    }

    //初始化人脸识别
    private void initFaces() {

        LogUtils.i("开始初始化人脸识别");
        if (FileUtils.fileIsExists(facesPath + files[0]) && FileUtils.fileIsExists(facesPath + files[1])) {
            listener = new EasyFace.OnSubFaceListener() {
                @Override
                public void onFaceNum(int faceNum) {
                    if (MyApplication.mDvrManager.mDvrCallBack != null && MyApplication.mDvrManager.bServiceConn) {
                        // 向主程序发送人脸数等信息
                        Bundle bundle = new Bundle();
                        bundle.putInt("FaceNumber", faceNum);
                        try {
                            MyApplication.mDvrManager.mDvrCallBack.doFaceInfo(bundle);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }

                    if (onFaceListener != null) {
                        // 返回到前台页面
                        onFaceListener.onFaceNumber((int) faceNum);
                    } else {
                        // 后台识别

                    }
                }

                public void onFaceNew(long listID, float[] faceFea) {
                    String str = String.format("Face Number: %d, %f", listID, faceFea[0]);
                    LogUtils.d(str);
                }

                public void onFaceOk(String faceID) {
                    LogUtils.d("faceID = " + faceID);
                    try {
                        Mp4v2Native.getInstance().faceStart(0, 1);

                        Bundle bundle = new Bundle();
                        bundle.putString("FaceID", faceID);
                        bundle.putInt("FaceNumber", FaceNumber);
                        MyApplication.mDvrManager.mDvrCallBack.doFaceResult(bundle);
                        LogUtils.d("onMessage向主程序反馈人脸识别结果");

//                            if (faceID.equals("0") || faceID.equals("-1")){
//                                Mp4v2Native.getInstance().faceStart(0, 1);
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("Result", 0);
//                                bundle.putInt("FaceNumber", FaceNumber);
//                                MyApplication.mDvrManager.mDvrCallBack.doFaceResult(bundle);
//                                LogUtils.d("onMessage向主程序反馈识别失败");
//                            }else {
//                                Mp4v2Native.getInstance().faceStart(0, 1);
//
//                                Bundle bundle = new Bundle();
//                                bundle.putString("FaceID", faceID);
//                                bundle.putInt("Result", 1);
//                                MyApplication.mDvrManager.mDvrCallBack.doFaceResult(bundle);
//                                LogUtils.d("onMessage向主程序反馈人脸识别结果");
//                            }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    if (onFaceListener != null) {
                        // 返回到前台页面
                        onFaceListener.onMessage(faceID);
                    }
                }

                @Override
                public void ServerConInfo(boolean conn) {
                    LogUtils.d("ServerConInfo = " + Boolean.toString(conn));
                    if (conn) {
                        // 连接人脸识别服务器成功,获取并设置传入图像函数指针
//                    Mp4v2Native.getInstance().setNativeProcessFrame(EasyFace.getInstance().getNativeProcessFrame());
//                        Mp4v2Native.getInstance().setNativeDrawFrame(EasyFace.getInstance().getNativeDrawFrame());
                    }

                }
            };

            EasyFace.getInstance().nativeInitFaceModePath(facesPath, faceServerIP, faceServerPort, faceDriverID, 100, listener);
//            Mp4v2Native.getInstance().setNativeGetFaceNumber(EasyFace.getInstance().getNativeGetFaceNumber());
//            Mp4v2Native.getInstance().faceStart(1, 0);
        } else
            initFaces();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d("onStartCommand: ");
//        initFaces();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        Mp4v2Native.getInstance().faceStart(0, 1);
        LogUtils.d("onDestroy: ");
        unregisterReceiver();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtils.d("onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        LogUtils.i("onRebind: ");
        super.onRebind(intent);
    }

    private class FaceServiceMsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_FACERECEIVER)) {
                // 收到人脸识别广播
                Bundle bundle = intent.getBundleExtra("Bundle");
                if (bundle != null) {
                    int Status = bundle.getInt("Status", 0);
                    if (Status == 1) {
                        // 开始人脸识别、打开页面
                        Intent intent1 = new Intent(mContext, FaceActivity.class);
                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent1);
                    } else if (Status == 0) {
                        if (onFaceListener != null) {
                            // 停止人脸识别
                            onFaceListener.onStopFace();
                        }
                    }
                }
            }
        }
    }

    private FaceServiceMsgReceiver faceServiceMsgReceiver = new FaceServiceMsgReceiver();
    private boolean mReceiverTag = false;   //广播接受者标识

    //代码中动态注册广播
    private void registerReceiver() {
        if (!mReceiverTag) {     //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
            IntentFilter mFileter = new IntentFilter();
            mReceiverTag = true;    //标识值 赋值为 true 表示广播已被注册
            mFileter.addAction(ACTION_FACERECEIVER);
            this.registerReceiver(faceServiceMsgReceiver, mFileter);
        }
    }

    //注销广播
    private void unregisterReceiver() {
        if (mReceiverTag) {   //判断广播是否注册
            mReceiverTag = false;   //Tag值 赋值为false 表示该广播已被注销
            this.unregisterReceiver(faceServiceMsgReceiver);   //注销广播
        }

    }
}
